//
//  OrganizationViewSelectController.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/5/5.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "OrganizationViewSelectController.h"
#import "ZJOrganizationSelectView.h"
#import "RecoverAdDetailViewController.h"

#define CellID @"OrganizationViewSelectController"
@interface OrganizationViewSelectController ()<ZJOrganizationSelectViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    CompanyInfoModel *_selectModel;
}
/** 机构选择框 */
@property (nonatomic, strong) ZJOrganizationSelectView *organizationSelectView;
/** 申请加入 */
@property (nonatomic, strong) UIButton *addButton;
/** 注册新机构 */
@property (nonatomic, strong) UIButton *registerNewCompany;
/** 索回机构管理权 */
@property (nonatomic, strong) UIButton *companyManager;
/** 返回 */
@property (nonatomic, strong) UIButton *back;
/** tableView */
@property (nonatomic, strong) UITableView *tableView;
/** 数据 */
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation OrganizationViewSelectController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"注册";
    self.view.backgroundColor = [UIColor zj_colorWithHexString:@"ffffff"];
    [self setupUI];
}

- (void)setupUI{
    //手机号提示
    UILabel *reminder = [UILabel new];
    reminder.text = @"机构选择 :";
    reminder.textColor = [UIColor textBlackColor];
    reminder.font = [UIFont titleTextFont];
    
    [self.view addSubview:reminder];
    reminder.sd_layout
    .topSpaceToView(self.view, LP_TopHeight + 23 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .heightIs([NSString heightWithTextFontSize:[UIFont titleTextFontSize]]);
    
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.organizationSelectView];
    [self.view addSubview:self.registerNewCompany];
    [self.view addSubview:self.companyManager];
    [self.view addSubview:self.back];
    
    
    self.organizationSelectView.sd_layout
    .topSpaceToView(reminder, 11 * [UIScreen zj_screenHScale])
    .leftEqualToView(reminder)
    .rightEqualToView(reminder)
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    self.addButton.sd_layout
    .leftEqualToView(reminder)
    .rightEqualToView(reminder)
    .topSpaceToView(reminder, 150 * [UIScreen zj_screenHScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    
    self.back.sd_layout
    .bottomSpaceToView(self.view, 25 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.addButton)
    .rightEqualToView(self.addButton)
    .heightRatioToView(self.addButton, 1);
    
    self.companyManager.sd_layout
    .bottomSpaceToView(self.back, 16 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.back)
    .rightEqualToView(self.back)
    .heightRatioToView(self.back, 1);
    
    self.registerNewCompany.sd_layout
    .bottomSpaceToView(self.companyManager, 16 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.companyManager)
    .rightEqualToView(self.companyManager)
    .heightRatioToView(self.companyManager, 1);
    
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    self.tableView.sd_layout
    .topSpaceToView(self.organizationSelectView, 1)
    .leftEqualToView(self.organizationSelectView)
    .rightEqualToView(self.organizationSelectView)
    .bottomSpaceToView(self.addButton, 1);
    
    
}

#pragma mark - ZJOrganizationSelectViewDelegate 协议方法

- (void)ZJOrganizationSelectViewDelegate_textFieldText:(NSString *)text{
    if (text.length > 0 && [self.organizationSelectView.textField isFirstResponder]) {
        
        [self netWorking];
        self.tableView.hidden = NO;
    }else{
        self.tableView.hidden = YES;
    }
}

//联想网络请求
- (void)netWorking{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"UNIT_NAME":self.organizationSelectView.textField.text};
    [NetWorkingManager postWithUrlString:[NetWorkingURL ListUnit] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"30000"] && [object objectForKey:@"ORG_UNITS"]) {
            weakSelf.dataArray = [[NSArray yy_modelArrayWithClass:[CompanyInfoModel class] json:object[@"ORG_UNITS"]] mutableCopy];
            
            [weakSelf netDataUpdateUI];
        }
        
    } Fail:^(id object) {
        
    }];
}

//根据网络请求下来的数据来修改界面
- (void)netDataUpdateUI{
    [self.tableView reloadData];
    if (self.dataArray.count == 0) {//网络请求没有请求下来数据(只能点击注册新机构)
        [self changeButtonType:self.addButton isCanSelect:NO];
        [self changeButtonType:self.registerNewCompany isCanSelect:YES];
        [self changeButtonType:self.companyManager isCanSelect:NO];
        return;
    }
    //选择tableViewcell
    if ([_selectModel.UNIT_NAME isEqualToString:self.organizationSelectView.textField.text]) {
        [self changeButtonType:self.addButton isCanSelect:YES];
        [self changeButtonType:self.registerNewCompany isCanSelect:NO];
        [self changeButtonType:self.companyManager isCanSelect:YES];
        return;
    }
    //未选中tableviewcell
    //判断第一个是输入的（可以点击 加入机构 和  索回权）
    if ([((CompanyInfoModel *)self.dataArray.firstObject).UNIT_NAME isEqualToString:self.organizationSelectView.textField.text]) {
        _selectModel = self.dataArray.firstObject;
        [self changeButtonType:self.addButton isCanSelect:YES];
        [self changeButtonType:self.registerNewCompany isCanSelect:NO];
        [self changeButtonType:self.companyManager isCanSelect:YES];
    }else{
        [self changeButtonType:self.addButton isCanSelect:NO];
        [self changeButtonType:self.registerNewCompany isCanSelect:YES];
        [self changeButtonType:self.companyManager isCanSelect:NO];
    }
}

//改变button的样式，根据是否能选中
- (void)changeButtonType:(UIButton *)button isCanSelect:(BOOL)isCanSelect{
    button.userInteractionEnabled = isCanSelect;
    if (isCanSelect) {//能够选中
        button.backgroundColor = [UIColor themeColor];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.layer.borderWidth = 0;
    }else{//不能够选中
        [button setTitleColor:[UIColor zj_colorWithHexString:@"a9a9a9"] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor clearColor];
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor zj_colorWithHexString:@"a9a9a9"].CGColor;
    }
}

#pragma mark - 点击事件
//申请加入
- (void)action_addButton{
    if (self.organizationSelectView.textField.text.length > 0) {
        [self netWorkingAdd];
    }
}

//申请加入的网络请求
- (void)netWorkingAdd{
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"ACCOUNTID":self.model.ACCOUNT_ID,@"UNIT_ID":_selectModel.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL addUnit] Parameter:dict Success:^(id object) {
        [YJProgressHUD hide];
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"30000"]) {//加入成功
            [YJProgressHUD showMessage:@"加入成功" inView:weakSelf.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            });
        } else if ([model.STATE isEqualToString:@"30004"]) {//机构未注册
           
            [YJProgressHUD showMessage:@"机构未注册" inView:weakSelf.view];
        }else{
            [YJProgressHUD showMessage:@"加入失败" inView:weakSelf.view];

        }
        
    } Fail:^(id object) {
        [YJProgressHUD showMessage:@"加入失败" inView:weakSelf.view];

    }];
}

//注册新机构
- (void)action_registerNewCompany{
    [YJProgressHUD show:@"注册中..." inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"ACCOUNT_ID":self.model.ACCOUNT_ID,
                           @"MOBILE":self.model.MOBILE,
                           @"UNIT_NAME":self.organizationSelectView.textField.text,
                           @"USER_ID":self.model.USER_ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL addOrgUnit] Parameter:dict Success:^(id object) {
        [YJProgressHUD hide];
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"30000"]) {//注册成功
            [YJProgressHUD showMessage:@"注册成功" inView:weakSelf.view];

            _selectModel.UNIT_NAME = weakSelf.organizationSelectView.textField.text;
            _selectModel.ID = [object objectForKey:@"UNIT_ID"];
            
            [weakSelf changeButtonType:weakSelf.addButton isCanSelect:YES];
            [weakSelf changeButtonType:weakSelf.registerNewCompany isCanSelect:NO];
            [weakSelf changeButtonType:weakSelf.companyManager isCanSelect:YES];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMessage:@"注册失败" inView:weakSelf.view];

    }];
}
//索回管理权
- (void)action_companyManager{
    RecoverAdDetailViewController *vc = [RecoverAdDetailViewController new];
    vc.companyModel = _selectModel;
    vc.userModel = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}
//跳过
- (void)action_back{
    
}

#pragma mark - UITableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyInfoModel *model = self.dataArray[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
    cell.textLabel.font = [UIFont titleTextFont];
    cell.textLabel.text = model.UNIT_NAME;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _selectModel = self.dataArray[indexPath.row];
    self.organizationSelectView.textField.text = _selectModel.UNIT_NAME;
    [self changeButtonType:self.addButton isCanSelect:YES];
    [self changeButtonType:self.registerNewCompany isCanSelect:NO];
    [self changeButtonType:self.companyManager isCanSelect:YES];
    self.tableView.hidden = YES;
    [self.view endEditing:YES];
}

#pragma mark - Setter


#pragma mark - Getters
- (ZJOrganizationSelectView *)organizationSelectView{
    if (_organizationSelectView == nil){
        _organizationSelectView = [[ZJOrganizationSelectView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _organizationSelectView.delegate = self;

    }
    return _organizationSelectView;
}

- (UIButton *)addButton{
    if (_addButton == nil){
        _addButton = [[UIButton alloc]init];
        [_addButton setTitle:@"立即加入" forState:UIControlStateNormal];
        [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _addButton.backgroundColor = [UIColor themeColor];
        _addButton.titleLabel.font = [UIFont titleTextFont];
        _addButton.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        [_addButton addTarget:self action:@selector(action_addButton) forControlEvents:UIControlEventTouchUpInside];
        [self changeButtonType:_addButton isCanSelect:NO];
    }
    return _addButton;
}

- (UIButton *)registerNewCompany{
    if (_registerNewCompany == nil){
        _registerNewCompany = [[UIButton alloc]init];
        [_registerNewCompany setTitle:@"注册新机构" forState:UIControlStateNormal];
        [_registerNewCompany setTitleColor:[UIColor zj_colorWithHexString:@"a9a9a9"] forState:UIControlStateNormal];
        _registerNewCompany.titleLabel.font = [UIFont titleTextFont];
        _registerNewCompany.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        _registerNewCompany.layer.borderColor = [UIColor zj_colorWithHexString:@"a9a9a9"].CGColor;
        _registerNewCompany.layer.borderWidth = 1;
        [_registerNewCompany addTarget:self action:@selector(action_registerNewCompany) forControlEvents:UIControlEventTouchUpInside];
        [self changeButtonType:_registerNewCompany isCanSelect:NO];
    }
    return _registerNewCompany;
}

- (UIButton *)companyManager{
    if (_companyManager == nil){
        _companyManager = [[UIButton alloc]init];
        [_companyManager setTitle:@"索回机构管理权" forState:UIControlStateNormal];
        [_companyManager setTitleColor:[UIColor zj_colorWithHexString:@"a9a9a9"] forState:UIControlStateNormal];
        _companyManager.titleLabel.font = [UIFont titleTextFont];
        _companyManager.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        _companyManager.layer.borderColor = [UIColor zj_colorWithHexString:@"a9a9a9"].CGColor;
        _companyManager.layer.borderWidth = 1;
        [_companyManager addTarget:self action:@selector(action_companyManager) forControlEvents:UIControlEventTouchUpInside];
        [self changeButtonType:_companyManager isCanSelect:NO];
    }
    return _companyManager;
}

- (UIButton *)back{
    if (_back == nil){
        _back = [[UIButton alloc]init];
        [_back setTitle:@" 跳过" forState:UIControlStateNormal];
        [_back setTitleColor:[UIColor zj_colorWithHexString:@"a9a9a9"] forState:UIControlStateNormal];
        [_back setImage:[UIImage imageNamed:@"sign_skip"] forState:UIControlStateNormal];
        _back.titleLabel.font = [UIFont titleTextFont];
        [_back addTarget:self action:@selector(action_back) forControlEvents:UIControlEventTouchUpInside];
    }
    return _back;
}
#pragma mark - Getters
- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height  - LP_TopHeight ) style:UITableViewStylePlain];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _tableView.layer.borderWidth = 1;
        _tableView.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        [_tableView  registerClass:[UITableViewCell class] forCellReuseIdentifier: CellID];
       
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil){
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}

@end


@implementation CompanyInfoModel

- (NSString *)description{
    return [self yy_modelDescription];
}

@end
